<?php

namespace app\controller\mobile;

use app\common\controller\JwtAuthorizedTrait;
use app\common\exception\CatchException;
use app\common\model\Admin;
use app\common\model\Authentication;
use app\common\model\User;
use app\common\util\AdminLoginInfo;

class MobileAuthorizedController extends MobileBaseController
{
    use JwtAuthorizedTrait;

    public User|null $user = null;

    protected function init()
    {

        //判断payload的type是否为该端的
        if (isset($this->payload->user_id)) {
            if (!(isset($this->payload->type) && $this->payload->type == 'mobile')) {
                throw new CatchException('无效的token，请重新登录', 607);
            }
        }

        $user_id = $this->payload->user_id ?? 0;
        $this->app->bind(User::class, function () use ($user_id) {
            $user = User::with(["authentication"])->find($user_id);
            if (!$user) {
                throw new CatchException('无效的用户信息，请重新登录', 608);
            }
            $pathInfo = "/" . request()->pathinfo();
            $checkPath = ["/mobile/forum/add", "/mobile/forum/answer", "/mobile/forum/follow", "/mobile/forum/like", "/mobile/user/follow", "/mobile/help_order/detail", "/mobile/help_order/sign", "/mobile/help_order/page", "/mobile/help_order/expert_submit", "/mobile/help_order/confirm", "/mobile/help_order/position"];
            if (in_array($pathInfo, $checkPath)) {
                if ($user->authentication && $user->authentication->expert_type == Authentication::EXPERT_TYPE_WORKER) {
                    if (!$user->authentication->head_img || !$user->head_img) {
                        throw new CatchException('请先上传用户照片', 621);
                    }
                }
            }


            $this->user = $user;

            //2024年3月16日09:08:26 检查用户有没有头像

            //AdminLoginInfo::setAdmin($user);
            return $user;
        });
    }

    /**
     * @param \app\common\model\base\User $user
     * @return \app\common\model\base\User
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function getUserOrNull()
    {
        $user = null;
        //判断payload的type是否为该端的
        if (isset($this->payload->user_id)) {
            if (isset($this->payload->type) && $this->payload->type == 'mobile') {
                $user_id = $this->payload->user_id ?? 0;
                $user = User::find($user_id);
            }
        }
        return $user;
    }
}
